`
https://leetcode.cn/problems/count-sub-islands/
`

/**
 * @param {number[][]} grid1
 * @param {number[][]} grid2
 * @return {number}
 */
var countSubIslands = function (grid1, grid2) {
  const m = grid1.length, n = grid1[0].length

  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (grid1[i][j] === 0 && grid2[i][j] === 1) {
        // 这个岛绝对不是子岛，淹掉
        dfs(grid2, i, j)
      }
    }
  }

  // 现在 grid2 中剩下的岛屿都是子岛，计算岛屿数量
  let res = 0
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (grid2[i][j] === 1) {
        res++
        dfs(grid2, i, j)
      }
    }
  }

  return res
};

function dfs(grid, i, j) {
  const m = grid.length, n = grid[0].length
  // 边界
  if (i < 0 || j < 0 || i >= m || j >= n) {
    return
  }

  // 遇到海
  if (grid[i][j] === 0) {
    return
  }

  grid[i][j] = 0

  dfs(grid, i + 1, j)
  dfs(grid, i - 1, j)
  dfs(grid, i, j + 1)
  dfs(grid, i, j - 1)
}